package config

import (
	"github.com/gin-gonic/gin"
	"log"
	"os"
	"path/filepath"
	"strings"
)

const (
	appModeEnv = "APP_ALT_MODE"
	appName    = "robot_alert" //项目名称-目前本地测试需要

	//框架环境 stable|TestingMode|DevelopMode|LocalMode
	ReleaseMode = "stable"
	TestingMode = "testing"
	DevelopMode = "develop"
	LocalMode   = "local"
)

var (
	//初始化日志变量
	Log logStruct

	//其他变量
	appMode    = "stable"
	configPath = "/etc/config/"
	modePath   = "prod"
	modeName   = LocalMode
)

func init() {
	mode := os.Getenv(appModeEnv)
	SetMode(mode)
}

func LoadConfig() {
	perConfSet()
	Log.init()
}

// 设置环境变量（gin框架环境）
func perConfSet() {
	appMode = os.Getenv(appModeEnv)
	//appMode = gin.Mode()

	switch appMode {
	case LocalMode:
		modePath = "local"
	case DevelopMode:
		modePath = "dev"
	case ReleaseMode:
		modePath = "prod"
	case TestingMode:
		modePath = "test"
	default:
		panic("APP_ALT_MODE unknown: " + appMode + " (available mode: stable testing develop local)")
	}

	workPath, err := os.Getwd()
	if err != nil {
		log.Panicf("get work path error %v", err)
	}
	findIndex := strings.Index(workPath, appName)
	if findIndex >= 0 {
		workPath = filepath.Join(workPath[:findIndex], appName)
	}
	configPath = filepath.Join(workPath, "config", modePath)
}

// SetMode sets gin mode according to input string.
func SetMode(value string) {
	switch value {
	case LocalMode:
	case DevelopMode:
		gin.SetMode(gin.DebugMode)
	case ReleaseMode:
		gin.SetMode(gin.ReleaseMode)
	case TestingMode:
		gin.SetMode(gin.TestMode)
	default:
		panic("APP_ALT_MODE unknown: " + value + " (available mode: stable testing develop local)")
	}

	modeName = value
}

func Mode() string {
	return modeName
}
